/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package hxg.portmgr.core.dao.impl.jaxb;

import hxg.portmgr.core.dao.IntfDAO;
import hxg.portmgr.core.device.Device;
import hxg.portmgr.core.device.intf.Intf;
import java.io.File;
import java.io.PrintWriter;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

/**
 *
 * @author hxg
 */
public class IntfDAOJaxbImpl implements IntfDAO {

    private static final Logger logger = Logger.getLogger(IntfDAOJaxbImpl.class.getName());
    //Device dev;

    @Override
    public void save(Device dev, Intf[] intfs) {
        if(intfs==null || intfs.length==0){
            removeIntfFile(dev);
        }
        try {
            JaxbEncodeIntf(getIntfFile(dev), intfs);
        } catch (JAXBException ex) {
            logger.log(Level.WARNING, "重要异常,无法保存接口列表,请仔细检查{0}", ex.getMessage());
        }
    }

    @Override
    public Intf[] getIntfs(Device dev) {
        File f = getIntfFile(dev);
        if (f.exists()) {
            Intf[] infs = JaxbDecodeIntf(f);
            for (Intf inf : infs) {
                inf.setDevice(dev);
            }
            return infs;
        } else {
            logger.log(Level.INFO, "设备无接口");
            return new Intf[0];
        }
    }

    private static void JaxbEncodeIntf(File f, Intf[] intfs) throws JAXBException {
        try (PrintWriter pw = new PrintWriter(f)) {
            JAXBContext jc = JAXBContext.newInstance(IntfListBean.class);
            Marshaller m = jc.createMarshaller();
            m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
            IntfListBean infs = new IntfListBean();
            infs.intfs = intfs;
            m.marshal(infs, pw);
            pw.flush();
        } catch (Exception ex) {
            logger.log(Level.INFO, null, ex);
        }
    }

    private static Intf[] JaxbDecodeIntf(File f) {
        try {
            JAXBContext jc = JAXBContext.newInstance(IntfListBean.class);
            Unmarshaller u = jc.createUnmarshaller();
            IntfListBean inflist = (IntfListBean) u.unmarshal(f);
            return inflist.intfs;
        } catch (JAXBException ex) {
            logger.log(Level.INFO, "没有找到指定文件{0}", f.getParent());
            return new Intf[0];
        }
    }

    public void removeIntfFile(Device dev) {
        getIntfFile(dev).delete();

    }

    private File getIntfFile(Device dev) {
        File f = new File("data\\intf\\" + dev.getIp() + ".xml");
        if (!f.getParentFile().exists()) {
            f.getParentFile().mkdirs();
        }
        return f;
    }

    @Override
    public void save() {
        
    }

    @Override
    public void load() {
        
    }

}
